//
//  UseDiscountViewController.m
//  PaiLeXiongProject
//
//  Created by 小獾科技 on 2017/9/11.
//  Copyright © 2017年 小獾科技. All rights reserved.
//

#import "UseDiscountViewController.h"
#import "MineDiscountCell.h"
#import "MindDiscountModel.h"
@interface UseDiscountViewController ()<UITableViewDelegate, UITableViewDataSource>
@property (nonatomic, strong) UIButton *discountBtn;
@property (nonatomic, strong) UIView *line;
@property (nonatomic, strong) UIButton *undiscountBtn;
@property (nonatomic, strong) UIView *line1;

@property (nonatomic, strong) UITableView *tableView;

@property (nonatomic, strong) NSMutableArray *disArray;//可用优惠券
@property (nonatomic, strong) NSMutableArray *undisArray;//不可用优惠券
@property (nonatomic, assign) NSInteger page;
@property (nonatomic, strong) LoadingView *load;
@property (nonatomic, copy) NSString *status;
@end

@implementation UseDiscountViewController

- (void)viewDidLoad {
    [super viewDidLoad];
//    [self configNavigation:@"使用优惠券"];
    self.title = @"使用优惠券";
    [self addBackItem];
    _disArray = [NSMutableArray arrayWithCapacity:0];
    _undisArray = [NSMutableArray arrayWithCapacity:0];
    _status = @"0";//可用
    _discountBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    _discountBtn.selected = YES;
    [_discountBtn setTitle:@"可用优惠券" forState:0];
    [_discountBtn setTitleColor:ColorFrom16(0xF5CB37) forState:0];
    _discountBtn.titleLabel.font = PFRFONT(14);
    [_discountBtn addTarget:self action:@selector(handleDisAction:) forControlEvents:UIControlEventTouchUpInside];
    [_discountBtn setEnlargeEdge:10];
    [self.view addSubview:_discountBtn];
    [_discountBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view).offset(12);
        make.left.equalTo(self.view).offset(50);
        make.width.equalTo(@87);
        make.height.equalTo(@20);
    }];
    
    _line = [UIView new];
    _line.backgroundColor = ColorFrom16(0xF5CB37);
    [self.view addSubview:_line];
    [_line mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_discountBtn.mas_bottom).offset(12);
        make.left.equalTo(self.view).offset(53);
        make.width.equalTo(@83);
        make.height.equalTo(@1);
    }];
    
    _undiscountBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [_undiscountBtn setTitle:@"不可用优惠券" forState:0];
    [_undiscountBtn setTitleColor:ColorFrom16(0x333333) forState:0];
    _undiscountBtn.titleLabel.font = PFRFONT(14);
    [_undiscountBtn addTarget:self action:@selector(handleUnAction:) forControlEvents:UIControlEventTouchUpInside];
    [_undiscountBtn setEnlargeEdge:10];
    [self.view addSubview:_undiscountBtn];
    [_undiscountBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view).offset(12);
        make.right.equalTo(self.view).offset(-40);
        make.width.equalTo(@108);
        make.height.equalTo(@20);
    }];
    
    _line1 = [UIView new];
//    _line1.backgroundColor = ColorFrom16(0xF5CB37);
    [self.view addSubview:_line1];
    [_line1 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_discountBtn.mas_bottom).offset(12);
        make.right.equalTo(self.view).offset(-44);
        make.width.equalTo(@100);
        make.height.equalTo(@1);
    }];
    
    UIView *aview = [UIView new];
    aview.backgroundColor = COLOR_BACKGROUND;
    [self.view addSubview:aview];
    [aview mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_line.mas_bottom);
        make.left.and.right.equalTo(self.view);
        make.height.equalTo(@1);
    }];
    
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 61 , GWIDTH, GHEIGHT - 125) style:UITableViewStylePlain];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.rowHeight = 107.8;
    _tableView.separatorColor = ColorClear;
    [self.view addSubview:_tableView];
    [_tableView registerClass:[MineDiscountCell class] forCellReuseIdentifier:@"cell"];
    
    _tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(doRefresh:)];
    _tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(doAppend:)];
    _tableView.mj_footer.hidden = YES;
    [_tableView.mj_header beginRefreshing];
    _page = 1;
    _load = [[LoadingView alloc] initWithFrame:CGRectMake(0, 61, GWIDTH, GHEIGHT - 97)];
    [_load setReminderLabelTitle:@"暂无优惠券~!" andImage:@"no_discount"];
    _load.hidden = YES;
    _load.refreshBtn.hidden = YES;
    [self.view addSubview:_load];
    
    if([GW_Request sharedInstance].noNetwork)
    {
        _load.hidden = NO;
    }
    
}

- (void)doAppend:(NSString *)status
{
    status = _status;
    [self startNetwork:status];
}

- (void)doRefresh:(NSString *)status
{
    _page = 1;
    status = _status;
    [self startNetwork:status];
}

- (void)startNetwork:(NSString *)status
{
  
    NSDictionary *param = @{@"gid":self.goodId,
                            @"gsum":self.gsum,
                            @"page": @(self.page)};
    [NetWork sendGetRequestURL:[NSString stringWithFormat:@"%@/coupons/GetCouponsZone?gid=%@&gsum=%@&page=%ld", GW_Domain, self.goodId, self.gsum, self.page] parameters:param completionBlockWithSuccess:^(NSDictionary *resultDict) {
        NSLog(@"优惠券 %@", resultDict);
        NSDictionary *dict = resultDict[@"data"];
        
        if(self.page == 1)
        {
            [self.undisArray removeAllObjects];
            [self.disArray removeAllObjects];
        }
        
        if([status isEqualToString:@"0"])
        {
            NSArray *arr = dict[@"usable"];
            //可用优惠券
            for (NSDictionary *dic in dict[@"usable"]) {
                MindDiscountModel *model = [GW_Tool getObjFromDictionary:dic byClassName:@"MindDiscountModel"];
                [_disArray addObject:model];
            }
            
            if(_disArray.count > 0)
                _load.hidden = YES;
            else
                _load.hidden = NO;
            
            if (arr.count < kPageSize) {
                [UIView animateWithDuration:0.3 animations:^{
                    self.tableView.mj_footer.hidden = YES;// 没有数据说明是最后一页了，隐藏上拉加载
                }];
            } else {
                self.tableView.mj_footer.hidden = NO;
            }
        }
        else
        {
            NSArray *arr = dict[@"nousable"];
            for (NSDictionary *dictionary in dict[@"nousable"]) {
                //不可用优惠券
                MindDiscountModel *model = [GW_Tool getObjFromDictionary:dictionary byClassName:@"MindDiscountModel"];
                [_undisArray addObject:model];
            }
            if(_undisArray.count > 0)
                _load.hidden = YES;
            else
                _load.hidden = NO;
            
            if (arr.count < kPageSize) {
                [UIView animateWithDuration:0.3 animations:^{
                    self.tableView.mj_footer.hidden = YES;// 没有数据说明是最后一页了，隐藏上拉加载
                }];
            } else {
                self.tableView.mj_footer.hidden = NO;
            }
        }
        self.page++;
        [_tableView reloadData];
        [_tableView.mj_footer endRefreshing];
        [_tableView.mj_header endRefreshing];
    } andFailure:^(NSError *error, NSString *errorMsg) {
        [_tableView.mj_header endRefreshing];
        NSLog(@"%@", error);
    }];
}


#pragma mark - UITableViewDelegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if(_discountBtn.selected == YES)
        return _disArray.count;
    else
        return _undisArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(_discountBtn.selected == YES)
    {//可用
        MindDiscountModel *model = self.disArray[indexPath.row];
        MineDiscountCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
        [cell configViewWithModel:model];
        return cell;
    }
    else
    {//不可用
        MindDiscountModel *model = self.undisArray[indexPath.row];
        MineDiscountCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
        [cell configViewWithModel:model];
        return cell;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(_discountBtn.selected == YES)
    {//可用
        MindDiscountModel *model = self.disArray[indexPath.row];
        if(self.block)
        {
            self.block(model.title, model.id);
            [self.navigationController popViewControllerAnimated:YES];
        }
    }
    else
    {
        
    }
}

//可用
- (void)handleDisAction:(UIButton *)sender
{
    sender.selected = YES;
    _undiscountBtn.selected = NO;

    [sender setTitleColor:ColorFrom16(0xF5CB37) forState:0];
    [_undiscountBtn setTitleColor:ColorFrom16(0x333333) forState:0];
    _line.backgroundColor = ColorFrom16(0xF5CB37);
    _line1.backgroundColor = ColorClear;
    _status = @"0";
    [self doRefresh:_status];
//    [_tableView reloadData];
//    if(self.disArray.count > 0)
//    {
//        _load.hidden = YES;
//    }
//    else
//        _load.hidden = NO;
}

//不可用
- (void)handleUnAction:(UIButton *)sender
{
    sender.selected = YES;
    _discountBtn.selected = NO;
    [sender setTitleColor:ColorFrom16(0xF5CB37) forState:0];
    [_discountBtn setTitleColor:ColorFrom16(0x333333) forState:0];
    _line1.backgroundColor = ColorFrom16(0xF5CB37);
    _line.backgroundColor = ColorClear;
//    [_tableView reloadData];
    _status = @"1";
    [self doRefresh:_status];
//    if(self.undisArray.count > 0)
//        _load.hidden = YES;
//    else
//        _load.hidden = NO;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
